import React, { Component } from 'react'
import { Route, Redirect, Switch } from 'react-router-dom'

export default class Index extends Component {
    render() {
        const { routes } = this.props
        // 筛选出不需要重定向的数据
        const routerList = routes.filter(item => !item.to)
        // 筛选出需要重定向的数据
        const redirectList = routes.filter(item => item.to)
        return (
            <Switch>
                {
                    routerList.map((item, index) => {
                        return <Route
                            key={index}
                            path={item.path}
                            render={() => {
                                // 拦截
                                if (item.auth && !sessionStorage.getItem('token')) {
                                    // 通过路由传参的方式来保存拦截的页面
                                    return <Redirect to={{
                                        pathname: "/login",
                                        state: {
                                            back: item.path
                                        }
                                    }}/>
                                } else {
                                    let Com = item.view
                                    if (item.children) {
                                        return <Com child={item.children} />
                                    } else {
                                        return <Com />
                                    }
                                }
                            }}
                        />
                    })
                }

                {
                    redirectList.map((item, index) => {
                        return <Redirect key={index}
                            to={item.to}
                            from={item.from}
                        />
                    })
                }
            </Switch>
        )
    }
}

